/*
 ============================================================================
 Page	     : 464-465
 Name        : flexmemb.c
 Date	     : 20210407
 Author      : Hbue 18060333
 Copyright   : Your copyright notice
 Description : 伸缩型数组成员(C99新增特性)
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

struct flex
{
	size_t count;
	double average;
	double scores[];	// 伸缩型数组成员
};

void showFlex(const struct flex * p);

int main(void)
{
	struct flex *pf1;
	struct flex *pf2;
	int n = 5;
	int total = 0;

	// 为结构和数组分配存储空间
	pf1 = malloc(sizeof(struct flex) + n * sizeof(double));
	pf1->count = n;
	for(int i = 0; i < n; i++)
	{
		pf1->scores[i] = 20.0 - i;
		total += pf1->scores[i];
	}
	pf1->average = total / n;
	showFlex(pf1);

	n = 9;
	total = 0;
	pf2 = malloc(sizeof(struct flex) + n * sizeof(double));
	pf2->count = n;
	for(int i = 0;i < n;i++)
	{
		pf2->scores[i] = 20.0 - i / 2.0;
		total += pf2->scores[i];
	}
	pf2->average = total / n;
	showFlex(pf2);
	free(pf1);
	free(pf2);

	return 0;
}

void showFlex(const struct flex * p)
{
	printf("Score : ");
	for(int i = 0; i < p->count; i++)
	{
		printf("%g ",p->scores[i]);
	}
	printf("\nAverage : %g\n", p->average);
}

